import subprocess
import sys
try:
    import websockets
except ImportError:

    # 使用 pip 安装 websockets 包
    # 使用 pip 安装 requirements.txt 中列出的所有依赖包
    subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
    # 重新导入 websockets 模块
    import websockets

# 在此之后，你可以继续使用项目的依赖包
import asyncio
from typing import List



#CMD print输出被缓冲,而无法打印： 在有些情况下，Python的标准输出（print输出）会被缓冲，因此并不会立即显示在命令行。你可以尝试将输出强制刷新，以便立即在命令行中看到输出。在每个print语句之后，添加以下代码：sys.stdout.flush()
#重写print函数
import builtins

# 保存原始的print函数
original_print = builtins.print

# 自定义的print函数
def sprint(*args, **kwargs):
    # 在这里添加你想要的额外逻辑
    # 比如，可以输出到文件，同时也调用原始的print函数
    original_print(*args, **kwargs)
    sys.stdout.flush()

# 将自定义的print函数设置为默认的print函数
builtins.print = sprint


class User:
    def __init__(self, ip, port, websocket, name=""):
        self.ip = ip
        self.port = port
        self.websocket = websocket
        self.name = name


class Online:
    userList: list = []

    async def handle_message(self, websocket, path):
        # 添加用户到userList中
        user = User(websocket.remote_address[0], websocket.remote_address[1], websocket)
        self.userList.append(user)
        print(f"User {user.ip}:{user.port} connected.")
        # for u in self.userList:
        #     try:
        #         print("sending...")
        #         if websocket.remote_address[1] != u.port:
        #             await u.websocket.send(f"User {user.ip}:{user.port} connected.")
        #         else:
        #             await u.websocket.send(f"welcome")
        #     except:
        #         pass

        try:
            async for message in websocket:
                # 处理接收到的消息
                print(f"Received message from {user.ip}:{user.port}: {message}")
                print(self.userList)
                sender = message.split(" ")[0]
                message = " ".join(message.split(" ")[1:])
                print(message)
                if message == "":
                    for u in self.userList:
                        try:
                            print("sending...")
                            if websocket.remote_address[0] == u.ip and websocket.remote_address[1] == u.port:
                                await u.websocket.send(f"你加入了聊天")
                                u.name = sender
                            else:
                                # await u.websocket.send(f"User {user.ip}:{user.port} says: {message}")
                                await u.websocket.send(f"{sender} 加入了聊天")
                        except:
                            pass
                else:
                    # 发送消息给所有在线用户
                    for u in self.userList:
                        try:
                            print("sending...")
                            if websocket.remote_address[0] == u.ip and websocket.remote_address[1] == u.port:
                                await u.websocket.send(f"你说: {message}")
                            else:
                                # await u.websocket.send(f"User {user.ip}:{user.port} says: {message}")
                                await u.websocket.send(f"{sender}: {message}")
                        except:
                            pass

                # 其他逻辑处理...

        finally:
            # 用户退出，从userList中移除
            self.userList.remove(user)
            print(f"User {user.ip}:{user.port} disconnected.")
            for u in self.userList:
                try:
                    print("sending...")
                    await u.websocket.send(f"{user.name} 退出了聊天")
                except:
                    pass

    async def run_server(self):
        start_server = websockets.serve(self.handle_message, "192.168.110.41", 8765)
        await start_server

        print("WebSocket server started.")
        await asyncio.Future()  # 持续等待连接


online = Online()
asyncio.run(online.run_server())
